﻿using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace jp110311.StorageModels
{
    public static class UserEntityService
    {
        private const string UserTableName = "users";
        private static bool _tableCreate;

        public static void AddUser(string zipCode, string nickName, string familyName, string givenName, string birthDate)
        {
            TableServiceContext context = GetDataServiceContext();
            context.AddObject( UserTableName, new UserEntity(zipCode,nickName)
                                        {
                                            FamilyName = familyName,
                                            GivenName = givenName,
                                            BirthDate = birthDate
                                        });
            var result = context.SaveChanges(SaveChangesOptions.None);
        }

        private static TableServiceContext GetDataServiceContext()
        {
            var tableClient = GetTableClient();
            var tableServiceContext = tableClient.GetDataServiceContext();
            tableServiceContext.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromMilliseconds(20));
            tableServiceContext.IgnoreResourceNotFoundException = true;

            if (DataServiceContextCreated != null)
            {
                DataServiceContextCreated( null, new DataServiceContextCreatedEventArgs(tableServiceContext));
            }
            return tableServiceContext;
        }

        public static event EventHandler<DataServiceContextCreatedEventArgs> DataServiceContextCreated;

        private static CloudTableClient GetTableClient()
        {
            CloudStorageAccount account = GetAccount();
            CloudTableClient tableClient = account.CreateCloudTableClient();
            if (!_tableCreate)
            {
                tableClient.CreateTableIfNotExist(UserTableName);
                _tableCreate = true;
            }
            return tableClient;
        }

        public static bool UseDevelopmentStorage;

        private static CloudStorageAccount GetAccount()
        {
            if (!RoleEnvironment.IsAvailable) return CloudStorageAccount.DevelopmentStorageAccount;
            if (UseDevelopmentStorage) return CloudStorageAccount.DevelopmentStorageAccount;
            return CloudStorageAccount.FromConfigurationSetting("StorageAccountConnection");
        }

        [CLSCompliant(false)]
        public static UserEntity FindUser(string zipCode, string familyName, string givenName, string birthDate)
        {
            var tableClient = GetTableClient();
            var tableServiceContext = tableClient.GetDataServiceContext();
            var q = tableServiceContext.CreateQuery<UserEntity>(UserTableName);
            IEnumerable<UserEntity> result;
            if (string.IsNullOrEmpty(birthDate))
            {
                result =
                    q.Where(
                        item => item.PartitionKey == zipCode
                                && item.FamilyName == familyName
                                && item.GivenName == givenName)
                        .AsEnumerable();
            }
            else
            {
                result = q.Where(
                    item => item.PartitionKey == zipCode
                            && item.FamilyName == familyName
                            && item.GivenName == givenName
                            && item.BirthDate==birthDate )
                            .AsEnumerable();
            }
            if (result.Count() == 1)
            {
                return result.Single();
            }
            return null;
        }
    }
}
